package com.example.controller;

import com.example.pojo.Dept;
import com.example.pojo.Result;
import com.example.service.DeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/depts")
@RestController
public class DeptController {
    private static Logger logger = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result list() {
        List<Dept> deptList = deptService.findAll();
//        System.out.println("查询全部部门信息");
        logger.info("查询全部部门信息");
        return Result.success(deptList);
    }

    /**
     * 删除部门（前端传递的请求参数名与服务端方法形参名一致时可以省略@RequestParam）
     *
     * @param deptId
     * @return
     */
    @DeleteMapping
    public Result delete(@RequestParam(value = "id", required = false) Integer deptId) {
        deptService.deleteById(deptId);
//        System.out.println("根据ID删除部门：" + deptId);
        logger.info("根据ID删除部门：" + deptId);
        return Result.success();
    }

    /**
     * 新增部门
     *
     * @param dept
     * @return
     */
    @PostMapping
    public Result addDept(@RequestBody Dept dept) {
//        System.out.println("新增部门：" + dept.getName());
        logger.info("新增部门：" + dept.getName());
        deptService.add(dept);
        return Result.success();
    }

    /**
     * 查询回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result queryDeptById(@PathVariable Integer id) {//通过url直接传递参数，使用{}来标记路径参数，使用@PathVariable获取参数
        Dept dept = deptService.getInfo(id);
//        System.out.println("查询部门信息:" + dept.getName());
        logger.info("查询部门信息:" + dept.getName());
        return Result.success(dept);
    }

    /**
     * 修改部门信息
     * @param dept
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Dept dept){
//        System.out.println("修改部门信息："+ dept.getName());
        logger.info("修改部门信息："+ dept.getName());
        deptService.update(dept);
        return Result.success();
    }
}

